package com.vipheyue.huaxue.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.vipheyue.huaxue.R;
import com.vipheyue.huaxue.fragment.ReNameFragment0;
import com.vipheyue.huaxue.fragment.ReNameFragment1;
import com.vipheyue.huaxue.fragment.ReNameFragment2;
import com.vipheyue.huaxue.fragment.ReNameFragment3;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private List<Fragment> fragmentArrayList;
    private FragmentManager fm;
    private Fragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        showFragmentIndex();
    }

    @OnClick({R.id.home_radioBtn_rename0, R.id.home_radioBtn_rename1, R.id.home_radioBtn_rename2, R.id.home_radioBtn_rename3})
    public void onClick(View view) {
        FragmentTransaction ft = fm.beginTransaction();
        switch (view.getId()) {
            case R.id.home_radioBtn_rename0:
                switchContent(fragmentArrayList.get(0));
                break;
            case R.id.home_radioBtn_rename2:
                switchContent(fragmentArrayList.get(2));
                break;
            case R.id.home_radioBtn_rename3:
                switchContent(fragmentArrayList.get(3));
                break;
        }
        ft.commit();
    }

    private void initView() {
        fragmentArrayList = new ArrayList<Fragment>();
        fragmentArrayList.add(new ReNameFragment0());
        fragmentArrayList.add(new ReNameFragment1());
        fragmentArrayList.add(new ReNameFragment2());
        fragmentArrayList.add(new ReNameFragment3());
    }

    private void showFragmentIndex() {
        fm = getSupportFragmentManager();
        currentFragment = fragmentArrayList.get(0);
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.content, fragmentArrayList.get(0));
        ft.commit();
    }

    public void switchContent(Fragment to) {
        if (currentFragment != to) {
//            FragmentTransaction transaction = fm.beginTransaction().setCustomAnimations(
//                    android.R.anim.fade_in, R.anim.slide_out_to_bottom);
            FragmentTransaction transaction = fm.beginTransaction();
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(currentFragment).add(R.id.content, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(currentFragment).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
            currentFragment = to;
        }
    }
}
